package logic

import (
	"context"

	"github.com/iriver/ai-offer/backend/internal/model"
	"github.com/iriver/ai-offer/backend/internal/svc"
	"github.com/iriver/ai-offer/backend/internal/types"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"gorm.io/gorm"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterRequest) (resp *types.UserResponse, err error) {
	// 验证邮箱是否已存在
	existingUser, err := l.svcCtx.UserStore.FindByEmail(req.Email)
	if err == nil && existingUser != nil {
		return nil, httpx.NewCodeError(types.ErrUserAlreadyExists, "用户邮箱已注册")
	} else if err != nil && err != model.ErrNotFound {
		l.Logger.Errorf("查询用户失败: %v", err)
		return nil, httpx.NewCodeError(types.ErrDatabase, "注册失败，请稍后重试")
	}

	// 检验角色是否有效
	if req.Role == "" {
		req.Role = string(model.RoleCandidate) // 默认为候选人
	}

	validRoles := map[string]bool{
		string(model.RoleCandidate):   true,
		string(model.RoleInterviewer): true,
		string(model.RoleAdmin):       true,
	}

	if !validRoles[req.Role] {
		return nil, types.NewValidateError("无效的用户角色")
	}

	// 密码加密
	passwordHash, err := model.HashPassword(req.Password)
	if err != nil {
		l.Logger.Errorf("密码加密失败: %v", err)
		return nil, httpx.NewCodeError(types.ErrPasswordEncrypt, "注册失败，请稍后重试")
	}

	// 创建用户
	user := &model.UserModel{
		Email:        req.Email,
		PasswordHash: passwordHash,
		Name:         req.Name,
		Role:         req.Role,
	}

	// 开启事务
	err = l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		// 创建用户并获取ID
		if err := tx.Create(user).Error; err != nil {
			l.Logger.Errorf("用户注册失败: %v", err)
			return err
		}
		return nil
	})

	if err != nil {
		l.Logger.Errorf("用户注册事务失败: %v", err)
		return nil, httpx.NewCodeError(types.ErrDatabase, "注册失败，请稍后重试")
	}

	// 返回用户信息
	resp = &types.UserResponse{
		Id:        user.ID,
		Email:     user.Email,
		Name:      user.Name,
		AvatarUrl: user.AvatarUrl,
		Role:      user.Role,
		CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt: user.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	return resp, nil
}
